package com.flysky.common;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

public class ExceptionHandler implements HandlerExceptionResolver {

	Logger flyskyLogger = Logger.getLogger(ExceptionHandler.class);
	@Override
	public ModelAndView resolveException(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception ex) {
		String errorMsg = null;
		try {
			errorMsg = this.getStackTrace(ex);
		} catch (IOException e) {
			e.printStackTrace();
		}
		this.flyskyLogger.error(ex.getMessage(), ex);
		ModelAndView view = new ModelAndView();
		if(ex instanceof UserUnLoginException){
			String frontUrl = request.getRequestURI();
			view.setViewName("login");
			view.addObject("frontUrl", frontUrl);
			return view; 
		}
		view.setViewName("exception");
		view.addObject("errorMsg", errorMsg);
		return view;
	}
	
	/**
	 * Get error trace stack.
	 * 
	 * @param t
	 * @return
	 * @throws IOException
	 */
	private String getStackTrace(Throwable t) throws IOException {
		String stackTrace = null;
		StringWriter sw = new StringWriter();
		PrintWriter pw = new PrintWriter(sw);
		t.printStackTrace(pw);
		pw.close();
		sw.close();
		stackTrace = sw.getBuffer().toString();
		return stackTrace;
	}
}
